<!-- 用户 -->

<script setup lang="ts">
import {ref, onMounted} from 'vue'
import Form from './form.vue'
import Detail from "./detail.vue";
import {MenuProps, notification} from 'ant-design-vue'
import * as apiUtil from '@/api/ApiUtils'
import * as authUtil from '@/ts/AuthUtils'
import * as orgApi from '@/api/AuthOrganizationApi'
import {TreeOption} from "@/ts/CommonTypes"

import * as roleApi from '@/api/AuthRoleApi'
import * as api from '@/api/AuthUserApi'
import {AuthUser, QueryData} from '@/api/AuthUserApi';

// 图标导入
import {
  DownloadOutlined,
  SearchOutlined,
  PlusOutlined,
  RedoOutlined,
  FormOutlined,
  DeleteOutlined,
  HistoryOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'

// ============ 响应式状态 ============
const columns = [
  {title: '账号', dataIndex: 'accountNo', key: 'accountNo',align:"center"},
  {title: '用户名', dataIndex: 'userName', key: 'userName',align:"center"},
  // { title: '昵称', dataIndex: 'nickName', key: 'nickName' },
  {title: '角色', dataIndex: 'roleName', key: 'roleName',align:"center"},
  {title: '组织', dataIndex: 'organizationName', key: 'organizationName',align:"center"},
  {title: '邮箱', dataIndex: 'email', key: 'email',align:"center"},
  {title: '手机号', dataIndex: 'phone', key: 'phone',align:"center"},
  {title: '创建时间', dataIndex: 'createTime', key: 'createTime',align:"center"},
  // { title: '修改时间', dataIndex: 'updateTime', key: 'updateTime' },
  {title: '操作', key: 'actionColumn',align:"center"},
]

const pageSizeOptions = ['10', '20', '50', '100']
const dataList = ref<AuthUser[]>([])
const currentId = ref<number | null>(null)
const queryData = ref<QueryData>(new QueryData());
const mode = ref({
  edit: false,
  delete: false,
  reset: false,
  review: false
})
const roleList = ref<any[]>([])
const orgTree = ref<TreeOption[]>([])

// ============ 方法定义 ============
function handleQueryList() {
  api.queryList(queryData.value).then((res) => {
    if (apiUtil.isSuccessed(res)) {
      const data = res.data
      dataList.value = data.records || []
      queryData.value.total = data.total
      queryData.value.current = data.current
      queryData.value.size = data.size
    } else {
      notification.error({
        message: '查询失败',
        description: res.message,
      })
    }
  })
}

function handleDelete() {
  api.deleteById(currentId.value!).then((res) => {
    if (apiUtil.isSuccessed(res)) {
      notification.success({message: '删除成功', description: '已删除'})
      handleCancel()
      handleQueryList()
    } else {
      notification.error({message: '删除失败', description: res.message})
    }
  })
}

function handleReset() {
  api.resetPasswordById(currentId.value!).then((res) => {
    if (apiUtil.isSuccessed(res)) {
      notification.success({message: '重置成功', description: '密码已重置'})
      handleCancel()
      handleQueryList()
    } else {
      notification.error({message: '重置失败', description: res.message})
    }
  })
}

function updateMode(modeValue: "edit" | "delete" | "review" | "reset", id = null) {
  currentId.value = id;
  switch (modeValue) {
    case "delete":
      mode.value.delete = true;
      break
    case "edit":
      mode.value.edit = true;
      break;
    case "reset":
      mode.value.reset = true;
      break;
    case "review":
      mode.value.review = true;
      break;
    default:
      break;
  }
}


function handleCancel() {
  mode.value.edit = false
  mode.value.delete = false
  mode.value.reset = false
  mode.value.review = false;
  currentId.value = null
}

function handleChange(current: number, size: number) {
  queryData.value.size = size
  queryData.value.current = current
  handleQueryList()
}

function handleOrgChanged(keys, e) {
  if (keys[0]) {
    queryData.value.organizationId = keys[0];
  } else {
    queryData.value.organizationId = null;
  }
  handleQueryList();
  console.log(keys, e);
}


function handleCleanQueryData() {
  queryData.value = new QueryData();
  handleQueryList();
}

function handleExport() {
  api.exportList(queryData.value)
}

// ============ 生命周期 ============
onMounted(() => {

  console.log("dddd", authUtil.permit('editAuthUser'));
  handleQueryList();

  roleApi.getSelectorOptions().then((res) => {
    if (apiUtil.isSuccessed(res)) {
      roleList.value = res.data
    }
  })

  orgApi.getTreeSelector().then((res) => {
    if (apiUtil.isSuccessed(res)) {
      orgTree.value = res.data
    }
  })
})
</script>
<template>
  <main class="page-main">
    <div class="padding-20">

      <a-row>
        <a-col :span="18">
          <!-- 查询、新增-->
          <a-form :label-col="{ style: { width: '80px' } }"
                  :model="queryData" autocomplete="off">
            <a-row>
              <a-col :span="8">
                <a-form-item label="组织" name="roleId" class="margin-top-10" >
                  <a-tree-select
                      v-model:value="queryData.organizationId"
                      :tree-data="orgTree"
                      show-search
                      tree-node-filter-prop="label"
                      tree-default-expand-all
                      placeholder="请选择组织">

                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="角色" name="roleId" class="margin-top-10">
                  <a-select v-model:value="queryData.roleId"
                            :options="roleList" placeholder="请选择角色"></a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="账号" name="accountNo" class="margin-top-10">
                  <a-input v-model:value="queryData.accountNo"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="用户名" name="userName" class="margin-top-10">
                  <a-input v-model:value="queryData.userName"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="邮箱" name="email" class="margin-top-10">
                  <a-input v-model:value="queryData.email"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="手机号" name="phone" class="margin-top-10">
                  <a-input v-model:value="queryData.phone"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>

        </a-col>
        <a-col :span="6">
          <div class="text-right margin-top-10">
            <a-space size="large">
              <a-button type="default" @click="handleCleanQueryData">
                <template #icon>
                  <RedoOutlined/>
                </template>
                重置
              </a-button>
              <a-button type="primary" @click="handleQueryList">
                <template #icon>
                  <SearchOutlined/>
                </template>
                查询
              </a-button>
              <a-button v-if="authUtil.permit('exportAuthUser')" type="dashed" @click="handleExport">
                <template #icon>
                  <DownloadOutlined/>
                </template>
                导出
              </a-button>
            </a-space>
          </div>

        </a-col>
      </a-row>

      <!-- 表格 -->
      <div class="line margin-top-10"></div>

      <div class="margin-top-10">
        <div class="text-right margin-top-10 margin-bottom-20">
          <a-button type="primary" @click="updateMode('edit')">
            <template #icon>
              <PlusOutlined/>
            </template>
            添加
          </a-button>
        </div>
        <a-table bordered
            :columns="columns" :data-source="dataList" :pagination="false"
                 class="ant-table-striped"
                 :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
        >
          <template #bodyCell="{ column, record  }">
            <template v-if="column.key === 'actionColumn'">
              <!--              内置账号 admin 不可删除-->
              <a-flex class="width" justify="space-around" v-if="record.accountNo !== 'admin'">
                <a-tooltip title="修改" v-if="authUtil.permit('editAuthUser')">
                  <a-button type="text" size="small" class="button-edit" @click="updateMode('edit',record.id)">
                    <template #icon>
                      <FormOutlined/>
                    </template>
                    修改
                  </a-button>
                </a-tooltip>

                <a-tooltip title="详情">
                  <a-button type="text" size="small" @click="updateMode('review',record.id)">
                    <template #icon>
                      <ExclamationCircleOutlined/>
                    </template>
                    详情
                  </a-button>
                </a-tooltip>

                <a-tooltip title="删除" v-if="authUtil.permit('deleteAuthUser')">
                  <a-button type="text" size="small" class="button-delete" @click="updateMode('delete',record.id)">
                    <template #icon>
                      <DeleteOutlined/>
                    </template>
                    删除
                  </a-button>
                </a-tooltip>

                <a-tooltip title="重置密码" v-if="authUtil.permit('resetPasswordAuthUser')">
                  <a-button type="text" size="small" @click="updateMode('reset',record.id)">
                    <template #icon>
                      <HistoryOutlined/>
                    </template>
                    重置密码
                  </a-button>
                </a-tooltip>
              </a-flex>
            </template>
          </template>
        </a-table>

        <!-- 分页 -->
        <div class="float-right margin-10-20">
          <a-pagination v-model:current="queryData.current" :total="queryData.total" show-size-changer
                        :page-size-options="pageSizeOptions" @showSizeChange="handleChange" @change="handleChange"/>
        </div>
        <div class="clear"></div>
      </div>

    </div>

    <!-- 新增、编辑的表单-->
    <a-drawer v-model:open="mode.edit" :title="currentId?'修改用户':'添加用户'" size="large">
      <Form :key="new Date()" :dataId="currentId" @close="handleCancel" @successed="handleQueryList"/>
    </a-drawer>

    <!-- 新增、编辑的表单-->
    <a-drawer v-model:open="mode.review" title="用户详情" size="large">
      <Detail :dataId="currentId" @close="handleCancel"/>
    </a-drawer>

    <!-- 删除 -->
    <a-modal v-model:open="mode.delete" title="确定删除">
      <span>确定删除用户吗？删除后数据不可恢复</span>
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" danger @click="handleDelete">删除</a-button>
      </template>
    </a-modal>

    <!-- 重置密码 -->
    <a-modal v-model:open="mode.reset" title="确定重置密码">
      <span>确定重置该用户的密码吗？</span>
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" danger @click="handleReset">重置</a-button>
      </template>
    </a-modal>

  </main>
</template>
<style scoped>

.ant-table-striped :deep(.table-striped) td {
  background-color: #f5f5f5;
}


</style>